import time

from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse

from utils.myjwt import myjwt
from utils.myredis import r


# from tools.myredis import r
# import time,json

class PermitionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print('中间件执行了')
        # 定义白名单
        wlist = [
            '/dce/',
            '/users/login/',
            '/users/register/',
            '/users/send_code/',
            '/users/password_login/',
            '/users/dingtalk_login/',
            '/users/dingtalk/callback/',  # 添加钉钉回调路径
            '/house/type/',
            '/house/list/',
            '/house/show/',
            '/users/house/recommend/',  # 添加推荐接口路径
        ]
        url = request.path
        print(f"Current URL: {url}")  # 添加URL调试信息
        
        # 检查是否在白名单中
        if url in wlist:
            return None
            
        try:
            token = request.headers.get('Authorization')
            print(f"Received token: {token}")  # 添加token调试信息
            
            if not token:
                return JsonResponse({'code': 409, 'msg': '缺少token'})
                
            data = myjwt.decode(token)
            print(f"Decoded token data: {data}")  # 添加解码数据调试信息
            
            if data is None:
                return JsonResponse({'code': 409, 'msg': 'token无效'})
            
            # 检查token是否过期
            current_time = int(time.time())
            if data['exp'] <= current_time:
                return JsonResponse({'code': 409, 'msg': 'token已过期'})

            # 检查token是否在黑名单中
            if r.get_str(token):
                return JsonResponse({'code': 409, 'msg': 'token已失效'})

        except Exception as e:
            print(f"Token validation error: {str(e)}")
            return JsonResponse({'code': 409, 'msg': '非法请求'})
        # #定义白名单
        # wlist = ['/login','/register','/send_code']
        # #获取token，url指的是接口地址
        # url = request.path
        # if url not in wlist:
        #     #解析验证
        #     try:
        #         token = request.headers.get('Authorization')
        #         data = mjwt.jwt_decode(token)
        #         #是否过期
        #         if int(time.time())> int(data['data']['exp']):
        #             return JsonResponse({"code":401})
        #         #是否过期
        #         #是否有权限操作
        #         # userid = data['data']['userid']
        #         #查询用户表，获取roleid
        #         #查询redis根据roleid
        #         #如果存在判断url是否在权限列表中 json.loads()
        #         #如果不存在，根据角色获取资源列表，存入redis

        #         #从redis中获取token,如果存在，说明已经退出，返回401没有权限操作
        #         # plist = r.get_str('user1promition')
        #         # if plist:
        #         #     plist = json.loads(plist)
        #         #     if url not in plist:
        #         #         return JsonResponse({"code":402})
        #         # else:
        #         #      return JsonResponse({"code":403})
        #     except:
        #         return JsonResponse({"code":401})
        # 是否过期
        # 是否退出
        # 是否有接口权限